package com.gxnzd.communityelderly.filter;

import com.gxnzd.communityelderly.commom.BaseContext;
import com.gxnzd.communityelderly.commom.JwtUtils;
import com.gxnzd.communityelderly.entity.Employee;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * ClassName: a
 * Package: com.gxnzd.communityelderly.filter
 * Description:
 *
 * @Author 胡海峰
 * @Create 2024/10/14 22:30
 * @Version 1.0
 */
@Component
public class UserInterceptor implements HandlerInterceptor {
    @Resource
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果是 OPTIONS 请求，让 OPTIONS 请求返回一个200状态码
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        // 获取 header 中的 Authorization 信息
        String authorityToken = request.getHeader("Authorization");
        //判断token是否有效
        if (jwtUtils.isTokenExpired(authorityToken)){
            Employee employee = jwtUtils.getUserInfoFromToken(authorityToken, Employee.class);
            BaseContext.setThreadLocal(employee.getEmpId());
            return true;
        }
        return false;
    }
}